package com.zjjc.QZEnergy.service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjjc.QZEnergy.domain.HeatData;
import com.zjjc.QZEnergy.mapper.HeatDataMapper;
import com.zjjc.QZEnergy.utils.DateUtils;
import com.zjjc.QZEnergy.vo.ReportData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

@Service
@Slf4j
@RequiredArgsConstructor
public class DataProcessServiceImpl extends ServiceImpl<HeatDataMapper, HeatData> implements IDataProcessService  {

    @Autowired
    HeatDataMapper heatDataMapper;

    @Value("${config.code}")
    private  String code;


    /**
     * 各企业每日总量上报
     * @param start
     * @param end
     * @param type 天然气/蒸汽
     * @param dateType 日报
     * @return
     */
    public ArrayList<ReportData> dailyDataSelect(Date start, Date end, String type,String dateType){
        ArrayList<HeatData> companyList = heatDataMapper.selectCompanyListByType(type);//根据公司类型(蒸汽/天然气)筛选出对应公司的相关信息
        ArrayList<ReportData> list = new ArrayList<>();
        SimpleDateFormat ymd = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat hms = new SimpleDateFormat("HHmmss");
        if (companyList.size() > 0){
            for (HeatData company : companyList) {
                Double value = 0.0;
                Double temp = 0.0;
                Double press = 0.0;
                ReportData reportData = new ReportData();
                HashMap<String, Object> map = new HashMap<>();
                reportData.setYmd(ymd.format(new Date()));
                reportData.setHms(hms.format(new Date()));
                reportData.setCode(type);
                reportData.setType(dateType);
                reportData.setObjType("600");
                reportData.setObjId(company.getCode());
                reportData.setTerminal("0");
                reportData.setTimestamp(String.valueOf(System.currentTimeMillis() / 1000));

                HeatData data = null;
                if (company.getRouter().length()>4){ //如果router长度大于4说明需要将多个站点相加 站点之间用英文逗号分隔
                    String[] strings = company.getRouter().split(",");
                    for (String string : strings) {
                        data = selectHeatData(start,end,string);
                        value += data.getValue();
                        press += data.getPress();
                        temp += data.getTemperature();
                    }
                    reportData.setValue(String.format("%.2f",value));
                    if ("steam".equals(type)){
                        map.put("temperature",String.format("%.2f",temp / strings.length));
                        map.put("press",String.format("%.2f",press / strings.length));
                        reportData.setValues(map);
                    }
                }else {
                    data = selectHeatData(start,end,company.getRouter());
                    reportData.setValue(String.format("%.2f",data.getValue()));
                    if ("steam".equals(type)){
                        map.put("temperature",String.format("%.2f",data.getTemperature()));
                        map.put("press",String.format("%.2f",data.getPress()));
                        reportData.setValues(map);
                    }
                }
                list.add(reportData);
            }
        }
        return list;
    }

    /**
     * 从历史表中根据条件查询数据
     * @param start
     * @param end
     * @param string
     * @return
     */
    private HeatData selectHeatData(Date start, Date end, String string) {
        HeatData heatData = heatDataMapper.selectHeatData(start, end, string);
        if (heatData == null){
            return heatDataMapper.selectHeatDataExceptZero(start, end, string);
        }
        return heatData;
    }

    /**
     * 上传记录新增
     * @param list
     * @param response  响应体信息
     * @param uploadUrl 天然气/蒸汽
     * @param appId
     */
    public void insertRecords(ArrayList<ReportData> list, String response, String uploadUrl, String appId) throws JsonProcessingException {
        Date date = new Date();
            String jsonStr = new ObjectMapper().writeValueAsString(list);
            heatDataMapper.insertRecords(jsonStr,response,uploadUrl,appId,date);
            System.out.println("======接口日志记录完成======");
    }

    /**
     * 月度上传数据整合 包括行业数据及月度总供热
     * @param start
     * @param end
     * @param type
     * @param dateType
     * @return
     */
    public ArrayList<ReportData> monthlyDataSelect(Date start, Date end, String type, String dateType) {
        SimpleDateFormat ymd = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat hms = new SimpleDateFormat("HHmmss");
        String ymdValue = ymd.format(new Date());
        String hmsValue = hms.format(new Date());

        HashMap<String, Object> map1 = new HashMap<>();
        ArrayList<HeatData> companyList = heatDataMapper.selectCompanyListByType(type); //筛选出所有蒸汽企业或天然气企业
        Double total = 0.0;  //供热单位总量
        HashMap<String, Double> map = new HashMap<>();
        for (HeatData heatData : companyList) { //对不同行业使用map进行统计
            Double value = 0.0;
            if(heatData.getRouter().length()>4){
                String[] strings = heatData.getRouter().split(",");
                for (String string : strings) {
                    HeatData tempData = selectHeatData(DateUtils.getFirstDayOfLastMonth().getTime(), DateUtils.getLastDayOfLastMonth().getTime(), string);
                    value += tempData.getValue();
                }
            }else {
                HeatData tempData = selectHeatData(DateUtils.getFirstDayOfLastMonth().getTime(), DateUtils.getLastDayOfLastMonth().getTime(), heatData.getRouter());
                value = tempData.getValue();
            }
            heatData.setValue(value);
            String area = heatData.getArea();
            total += heatData.getValue();
            if(!map.containsKey(area)) {
                map.put(area,heatData.getValue());
            }else {
                value = map.get(area);
                value += heatData.getValue();
                map.put(area,value);
            }
        }

        ArrayList<ReportData> list = new ArrayList<>();
        for (String key : map.keySet()) {
            //对行业数据进行上传
            ReportData areaData = new ReportData();
            areaData.setYmd(ymdValue);
            areaData.setHms(hmsValue);
            areaData.setCode(type);
            areaData.setType(dateType);
            areaData.setObjType("602");  //行业数据
            areaData.setObjId("330803"); //企业所在区块代码 柯城330802 衢江330803 常山330822 开化330824 龙游330825 江山330881
            areaData.setTerminal(key);
            areaData.setTimestamp(String.valueOf(System.currentTimeMillis() / 1000));
            areaData.setValue(String.format("%.2f",map.get(key)));
            areaData.setValues(map1);
            list.add(areaData);
        }
        //对总量进行上传
        ReportData totalData = new ReportData();
        totalData.setYmd(ymdValue);
        totalData.setHms(hmsValue);
        totalData.setCode(type);
        totalData.setType(dateType);
        totalData.setObjType("600");
        totalData.setObjId(code);
        totalData.setTerminal("0");  //总量数据
        totalData.setTimestamp(String.valueOf(System.currentTimeMillis() / 1000));
        totalData.setValue(String.format("%.2f",total));
        totalData.setValues(map1);

        list.add(totalData);
        return list;
    }

}
